package com.jeesite.modules.stock.service;

import com.jeesite.common.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Component
public class StockDataSync {

    protected Logger log = LoggerFactory.getLogger(StockDataSync.class);

    @Autowired
    private DataTrans dataTrans;

    public void sync() {
        Thread.ofVirtual().start(() -> {
            while (true) {
                ThreadUtils.sleep(1000 * 20);
                SimpleDateFormat fr = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat timeFr = new SimpleDateFormat("HH:mm:ss");
                String date = fr.format(new Date());
                String time = timeFr.format(new Date());
                if (time.compareTo("15:00:00") > 0 && time.compareTo("15:40:00") < 0) {
                    continue;
                }
                LocalDate today = LocalDate.now(ZoneId.systemDefault());
                String dayOfWeek = today.getDayOfWeek().toString();
                if ("Saturday".equalsIgnoreCase(dayOfWeek)
                        || "Sunday".equalsIgnoreCase(dayOfWeek)) {
                    continue;
                }

                try {
                    dataTrans.dataTrans("group_daily_data", "date='" + date + "'");
                    dataTrans.dataTrans("group_weekly_data", "date='" + date + "'");
                    dataTrans.dataTrans("group_monthly_data", "date='" + date + "'");

                    dataTrans.dataTrans("stock_daily_data", "date='" + date + "'");
                    dataTrans.dataTrans("stock_weekly_data", "date='" + date + "'");
                    dataTrans.dataTrans("stock_monthly_data", "date='" + date + "'");

                    if (dataTrans.dataChange()) {

                        dataTrans.deleteData("stock_latest_data", "1=1");
                        dataTrans.dataTrans("stock_latest_data", "1=1");

                        dataTrans.deleteData("stocks_informations", "1=1");
                        dataTrans.dataTrans("stocks_informations", "1=1");
                    }
                    ThreadUtils.sleep(1000 * 1200);
                } catch (Exception e) {
                    log.error("同步数据失败：errMsg:{}", e.getMessage(), e);
                }
            }
        });
    }
}
